package com.cxf.windex.task;

import com.cxf.windex.base.bean.LockInfo;
import com.cxf.windex.base.constant.LockConstant;
import com.cxf.windex.biz.CxfAccountBiz;
import com.cxf.windex.entity.CxfAccount;
import com.cxf.windex.entity.CxfUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

import java.util.concurrent.Future;

/**
 * @author chenxf
 * @date 4/12/2018
 * @description 注册异步任务
 */
@Component
public class RegisterTask {
  public static final Logger logger = LoggerFactory.getLogger(RegisterTask.class);

  @Autowired
  private CxfAccountBiz cxfAccountBiz;
  /**
   * 注册 初始化帐户
   * @param user
   * @return
   * @throws Exception
   */
  @Async
  public Future<String> doRegisterTask(CxfUser user)  {
    logger.debug("开始做注册 资金初始化");
    //用户资金锁
    LockInfo lockInfo = new LockInfo(LockConstant.MONEY_LOCK+user.getId());
    try {
      long start = System.currentTimeMillis();
      CxfAccount cxfAccount = new CxfAccount();
      cxfAccount.setUserid(user.getId());
      cxfAccount.setName(user.getName());
      cxfAccountBiz.insertSelective(cxfAccount);
      long end = System.currentTimeMillis();
      logger.debug("完成注册 资金初始化，耗时：" + (end - start) + "毫秒");
    } catch (Exception e) {
      logger.error("注册 资金初始化失败 e={}",e.getMessage());
    }finally {
      lockInfo.unlock();
    }
    return new AsyncResult<>("资金初始化完成");
  }

}
